﻿#include "ssContextSchedule.h"


namespace StarSeeker
{

ssContextSchedule::ssContextSchedule()
	:m_main(0),m_currrent(0)
{
#ifdef SS_USE_WINDOWS
	m_main = ConvertThreadToFiber(0);
#else
	m_main = &m_mainUC;
#endif
}

ssContextSchedule::~ssContextSchedule()
{
	Release();
}

void ssContextSchedule::AddContext(ssContext* pContext, unsigned int stackSize)
{
	if (pContext)
	{
		if (pContext->State() == CS_NULL)
		{
			pContext->Create(m_main, stackSize);
		}
		m_list.push_back(pContext);
	}
}

void ssContextSchedule::RunFrame()
{
	if (!m_list.empty())
	{
		for (std::list<ssContext*>::iterator i=m_list.begin(); i!=m_list.end();)
		{
			if ((*i)->State() == CS_END)
			{
				delete (*i);
				i = m_list.erase(i);
			}
			else
			{
				(*i)->Run();
				++i;
			}
		}
	}
}

void ssContextSchedule::RunLoop()
{
	while (!m_list.empty())
	{
		RunFrame();
	}
}

void ssContextSchedule::Release()
{
#ifdef SS_USE_WINDOWS
	if (m_main)
	{
		ConvertFiberToThread();
		m_main = 0;
	}
#endif
}

}
